#include "PlayerItem.h"
#include <QPixmap>
#include <QPainter>
#include <QTimer>
#include <QtGui/QCursor>

QString toTimeStr(QString data)
{
    char time[64] = "";
    int h = 0, min = 0, sec = 0;
    int pts = atoi(data.toStdString().c_str());
    if(pts < 60)
    {
        h = 0;
        min = 0;
        sec = pts;

    }else if(pts < 3600){

        h = 0;
        min = pts/60;
        sec = pts%60;
    }else{

        h = pts/3600;
        min = pts%3600/60;
        sec = pts%3600%60;
    }

    sprintf(time, "%02d:%02d:%02d", h, min, sec);

    QString timeStr = time;

    return timeStr;
}

PlayerItem::PlayerItem()
{
    mousePressPos.setX(-1);
    setAcceptedMouseButtons(Qt::LeftButton| Qt::RightButton| Qt::MiddleButton);

    player = new Qffplayer();

    connect(player, &Qffplayer::sigPlayerCb, this, &PlayerItem::onPlayerCb);
    connect(player, &Qffplayer::sigDisplay,this, &PlayerItem::onDisplay, Qt::QueuedConnection);
    return;
}

QVariantMap PlayerItem::getMediaInfo()
{
    std::shared_ptr<MediaInfo> mediainfo = player->get_mediainfo();
    QVariantMap  infoMap;

    infoMap.insert("frame_rate",mediainfo.get()->vinfo.framerate);
    infoMap.insert("vcodec_name",mediainfo.get()->vinfo.codec_name);
    QString resolution = QString::number(mediainfo.get()->vinfo.width)+"x"+QString::number(mediainfo.get()->vinfo.height);
    infoMap.insert("resolution",resolution);
    infoMap.insert("pix_format",mediainfo.get()->vinfo.pix_format);
    QString v_br = QString::number(mediainfo.get()->vinfo.bit_rate/1000)+"Kb/s";
    infoMap.insert("v_bit_rate",v_br);

    infoMap.insert("sample_rate",mediainfo.get()->ainfo.sample_rate);
    infoMap.insert("acodec_name",mediainfo.get()->ainfo.codec_name);
    infoMap.insert("channel",mediainfo.get()->ainfo.channel);
    infoMap.insert("sample_bits",mediainfo.get()->ainfo.sample_bits);
    QString a_br = QString::number(mediainfo.get()->ainfo.bit_rate/1000)+"Kb/s";
    infoMap.insert("a_bit_rate",a_br);
    return infoMap;
}

bool PlayerItem::setFaceDetect()
{
    bool ret = player->get_facedetect();
    player->set_facedetect(!ret);

    return !ret;
}

void PlayerItem::onPlayerCb(int type, QString data, int w, int h)
{
    if(type == 1)
    {
        isStop = true;
        stopPlay();

    }else if(type == 0){

        isStop = false;

    }else if(type == 2){

        emit setTime2qml(0 ,toTimeStr(data), atoi(data.toStdString().c_str()));

    }else if(type == 3){

        emit setTime2qml(1, toTimeStr(data), atoi(data.toStdString().c_str()));

    }

    return ;
}

PlayerItem::~PlayerItem()
{
    return;
}

void PlayerItem::stopPlay()
{
    if(mu.tryLock()){

        isPause = false;
        player->stopPlay();
        while(isStop == false){
            int ms = 10;
            QEventLoop loop;
            QTimer::singleShot(ms, &loop, &QEventLoop::quit);
            loop.exec();
        }
        setRecord();
        update(); // 清除空间上的图片
        isPlaying = false;
        isScale = false;
        mousePressPos.setX(-1);
        mu.unlock();
    }

    this->speed = 1;
    this->showWidth = -1;
    this->showHeight = -1;
    this->isMosic = false;
    this->isFrameDisplay = false;
    this->isPause = false;
    this->maskStr = "";
    this->isRecording = false;
    this->isCarNO = false;
    emit stopPlay2qml("");
    return ;

}

#define UNUSE(var) ((void)(var))

void PlayerItem::onDisplay(QImage _img, long pts)
{
    UNUSE(pts);
    if(isStop){
        return ;
    }

    displayImg = orgImg = _img;

    if(this->isScale)
    {
        displayImg = orgImg.copy(assistantRec.x(), assistantRec.y(), assistantRec.width(),assistantRec.height());
        displayImg = displayImg.scaled(_img.width(), _img.height());
    }

    if(isMosic)
    {
        displayImg = set_cv_mosic(displayImg, assistantRec.x(), assistantRec.y(), assistantRec.width(), assistantRec.height());
    }

    if(isTransform)
    {
        displayImg = set_transform(displayImg, assistantRec.x(), assistantRec.y());
    }

    if(this->maskStr != "")
    {
        displayImg = add_mask(displayImg, maskStr, assistantRec.x(), assistantRec.y());
    }
    if(isCarNO)
        displayImg = carNo(displayImg);

    if(this->isPlaying && getRecord())
    {
        player->transcode2h264(displayImg);
    }

    update();
}

void PlayerItem::paint(QPainter *painter)
{
    if(isStop){
        return ;
    }

    if(painter->window().width() != winWidth || painter->window().height() != winHeight )  // 如果窗口缩放,鼠标的坐标也要缩放
    {
        float mousex = (float)(painter->window().width())/winWidth;
        float mousey = (float)(painter->window().height())/winHeight;

        mousePressPos.setX(mousePressPos.x()*mousex);
        mousePressPos.setY(mousePressPos.y()*mousey);

        mouseCurrentPos.setX(mouseCurrentPos.x()*mousex);
        mouseCurrentPos.setY(mouseCurrentPos.y()*mousey);

        winWidth = this->width();
        winHeight = this->height();
    }

    /**  计算图片显示的x y坐标, 宽高**/
    float aspect = (float)(displayImg.width())/displayImg.height();
    if(aspect > 1.00)
    {
        showWidth = this->width();
        showHeight = showWidth/aspect;
    }else{

        showHeight = this->height();
        showWidth = showHeight*aspect;
    }

    int x = 0, y = 0;
    if(showWidth < this->width()){
        x = (this->width()-showWidth)/2;
    }
    if(showHeight < this->height()){
        y = (this->height()-showHeight)/2;
    }
    /**  end **/

    QPixmap pixmap;
    if(mousePressPos.x() >= 0 && mouseCurrentPos.x() >=0 && mousePressPos.y() >=0 &&  this->isScale == false){   // 鼠标在播放窗口上画框

        float xfac = ((float)displayImg.width())/showWidth;
        float yfac = ((float)displayImg.height())/showHeight;
        QRect rect((mousePressPos.x()-x)*xfac, (mousePressPos.y()-y)*yfac, (mouseCurrentPos.x()-mousePressPos.x())*xfac,(mouseCurrentPos.y()-mousePressPos.y())*yfac);
        assistantRec = rect;
        QImage t = displayImg.copy();
        QPainter p(&t);
        p.setPen(QPen(Qt::red, 2));
        p.drawRect(assistantRec);
        pixmap = QPixmap::fromImage(t);

    }else{
        pixmap = QPixmap::fromImage(displayImg);
    }

    painter->drawPixmap(x,y,showWidth,showHeight,pixmap);
    return ;
}

void PlayerItem::mouseMoveEvent(QMouseEvent *e)
{
    if(isPlaying == false || isScale)
        return ;
    mouseCurrentPos = e->pos();
    if(isMosic)
    {
        displayImg = set_cv_mosic(displayImg, assistantRec.x(), assistantRec.y(), assistantRec.width(), assistantRec.height());
    }
    if(isPause || isFrameDisplay)  // 暂停或者逐帧播放，刷新播放窗口， 为了辅助框显示出来
        update();
}

void PlayerItem::mousePressEvent(QMouseEvent *e)
{

    if(isPlaying == false || isScale)
        return ;

    mousePressPos = e->pos();
    mouseCurrentPos.setX(-1);

    if(isPause||isFrameDisplay)
        update();
}

void PlayerItem::startPlay(QString url)
{
    if(url.length() == 0)
        return ;
    if(isPlaying == true)
        stopPlay();

    player->StartPlay(url);
    isPlaying = true;
    return ;
}
